/*
 * @描述: 基本设置页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { Form, Input, Upload, Select, Button, message } from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
import GeographicView from './GeographicView';
import PhoneView from './PhoneView';
// import { getTimeDistance } from '@/utils/utils';

const FormItem = Form.Item;
const { Option } = Select;

function handleChange() { }; // NOSONAR

function beforeUpload(file) {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
  if (!isImage) {
    message.error(formatMessage({ id: 'app.settings.basic.upload.isimage' }));
  }
  const isst10M = file.size / 1024 / 1024 < 10;
  if (!isst10M) {
    message.error(formatMessage({ id: 'app.settings.basic.upload.isst10m' }));
  }
  const isNotEmpty = file.size > 0;
  if (!isNotEmpty) {
    message.error(formatMessage({ id: 'app.settings.basic.upload.isnotempty' }));
  }
  return isImage && isst10M && isNotEmpty;
}

const props = {
  name: 'file',
  showUploadList: false,
  accept: "image/*",
  beforeUpload: beforeUpload,
  action: '/api/file/file/uploadFile',
  headers: {
    Authorization: 'Bearer ' + localStorage.getItem('mscode_token'),
    RoleCode: localStorage.getItem('mscode_authority'),
  },
  onChange(info) {
    if (info.file.status === 'done') {
      handleChange();
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }
};

// 头像组件 方便以后独立，增加裁剪之类的功能
const AvatarView = ({ avatar, sysUserId }) => (
  <Fragment>
    <div className={styles.avatar_title}>
      <FormattedMessage id="app.settings.basic.avatar" defaultMessage="Avatar" />
    </div>
    <div className={styles.avatar}>
      <img src={avatar + '?token=' + localStorage.getItem('mscode_token')} alt="avatar" />
    </div>
    <Upload {...props} data={{ id: sysUserId, uploadType: 'avatar' }}>
      <div className={styles.button_view}>
        <Button icon="upload" type="primary" ghost>
          <FormattedMessage id="app.settings.basic.change-avatar" defaultMessage="Change avatar" />
        </Button>
      </div>
    </Upload>
  </Fragment>
);

const validatorGeographic = (rule, value, callback) => {
  const { province, city } = value;
  if (!province.key) {
    callback(formatMessage({ id: 'app.settings.basic.province.required' }));
  }
  if (!city.key) {
    callback(formatMessage({ id: 'app.settings.basic.city.required' }));
  }
  callback();
};

const validatorPhone = (rule, value, callback) => {
  if (value === null) {
    message.warning(formatMessage({ id: 'app.settings.basic.area-code.required' }));
    return;
  }
  const values = value.split('-');
  if (!values[0]) {
    callback(formatMessage({ id: 'app.settings.basic.area-code.required' }));
  }
  if (!values[1]) {
    callback(formatMessage({ id: 'app.settings.basic.phone.required' }));
  }
  callback();
};

@connect(({ user }) => ({
  currentUser: user.currentUser
}))
@Form.create()
class BaseView extends Component {
  componentDidMount() {
    this.setBaseInfo();
    handleChange = () => {
      const { dispatch } = this.props;
      dispatch({
        type: 'user/fetchCurrent'
      });
    }
  }

  setBaseInfo = () => {
    const { currentUser, form } = this.props;
    Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = currentUser[key] || null;
      form.setFieldsValue(obj);
    });
  };

  getAvatarURL() {
    const { currentUser } = this.props;
    if (currentUser.avatar) {
      return currentUser.avatar;
    }
  }

  getViewDom = ref => {
    this.view = ref;
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, dispatch, currentUser } = this.props;
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        dispatch({
          type: 'account/update',
          payload: {
            nickname: values.nickname,
            profile: values.profile,
            provinceRegionCode: values.geographic.province.key,
            cityRegionCode: values.geographic.city.key,
            address: values.address,
            phone: values.phone,
            id: currentUser.id
          }
        }).then(response => {
          if (response.message == 'success') {
            message.success(formatMessage({ id: 'app.common.edit-success' }));
          } else {
            message.warning(response.message);
          }
          dispatch({
            type: 'user/fetchCurrent'
          });
        });
      }
    });
  };

  render() {
    const { form: { getFieldDecorator }, currentUser } = this.props;
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form layout="vertical" onSubmit={this.handleSubmit}>
            <FormItem label={formatMessage({ id: 'app.settings.basic.nickname' })}>
              {getFieldDecorator('nickname', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.basic.nickname.required' })
                  },
                  {
                    max: 64,
                    message: formatMessage({ id: 'app.settings.basic.nickname.length' })
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.phone' })}>
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true
                  },
                  {
                    validator: validatorPhone
                  }
                ]
              })(<PhoneView />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.geographic' })}>
              {getFieldDecorator('geographic', {
                rules: [
                  {
                    required: true
                  },
                  {
                    validator: validatorGeographic
                  }
                ]
              })(<GeographicView />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.address' })}>
              {getFieldDecorator('address', {
                rules: [
                  {
                    message: formatMessage({ id: 'app.settings.basic.address.length' }),
                    max: 40
                  }
                ]
              })(<Input />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.profile' })}>
              {getFieldDecorator('profile', {
                rules: [
                  {
                    message: formatMessage({ id: 'app.settings.basic.profile.length' }),
                    max: 256
                  }
                ]
              })(
                <Input.TextArea
                  placeholder={formatMessage({ id: 'app.settings.basic.profile-placeholder' })}
                  rows={4}
                />
              )}
            </FormItem>
            <Button type="primary" htmlType="submit">
              <FormattedMessage id="app.settings.basic.update" defaultMessage="Update Information" />
            </Button>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView avatar={this.getAvatarURL()} sysUserId={currentUser.id} />
        </div>
      </div>
    );
  }
}

export default BaseView;